import time
from typing import Dict, Any, Optional
from tenacity import retry, stop_after_attempt, wait_exponential
from intelli_port.commons.audit import audit_event, write_ops_log
from intelli_port.commons.config import load_settings
import httpx

@retry(reraise=False, stop=stop_after_attempt(3), wait=wait_exponential(multiplier=0.2, min=0.2, max=2.0))
def rebook_order(payload: Dict[str, Any], idem_key: Optional[str] = None) -> Dict[str, Any]:
    s = load_settings()
    if getattr(s, "rebook_base_url", ""):
        try:
            headers = {"Authorization": f"Bearer {s.external_auth_token}"} if getattr(s, "external_auth_token", "") else {}
            if idem_key:
                headers["X-Idempotency-Key"] = str(idem_key)
            with httpx.Client(timeout=float(getattr(s, "external_timeout_s", 2.0))) as client:
                r = client.post(s.rebook_base_url.rstrip("/") + "/rebook", json=payload, headers=headers)
                if r.status_code == 200:
                    return r.json()
        except Exception:
            pass
    order_id = str(int(time.time() * 1000))
    write_ops_log("INFO", "rebook.create", {"order_id": order_id, "payload": payload})
    audit_event("rebook", "order", "rebook", payload, result="success")
    return {"order_id": order_id, "status": "succeeded"}